<?php

// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------
namespace app\order\event;


/**
 *  商城自动结算钩子
 *  @author hu
 */
class Settlement {
    
    /**
     * 批量自动结算 (T+1)
     * 如有分佣，这里分佣要到账
     * @author 晓风
     * @return int
     */
    public function run($playload = [])
    {        
         //读取状态为完成的进行结算
        $config = \app\admin\model\Module::getConfig('order');
        $config['order_receive'] = (int)$config['order_receive'] + 1;
        $config['refund_day'] = (int)$config['refund_day'] + 1;
        
        $shipping_timeout = ($config['order_receive'] <=0 ? 7 : $config['order_receive']) * 86400;        
        $refund_timeout =   ($config['refund_day'] <=0 ? 7 : $config['refund_day'])  * 86400;
        
        $time = time();        
        //商城部分订单       
        $orders = \app\common\model\Order::view("order",true)
            ->view("order_goods_express",false,"order.order_sn = order_goods_express.order_sn")
            ->where('order.order_type', 'in', [3])
            ->where('order.status', 'in', [3,4,6])
            ->where('order.pay_time', '<', $time -  $refund_timeout)
            ->where('order_goods_express.shipping_time','<',$time - $shipping_timeout )
            ->where('order.settle_status', 0)
             //排除售后中的订单
            ->where("order.order_sn","not in",function($query){                
                $query->name("order_refund")->where("status","in",[0,1,2])->field("order_sn");
            }) 
            ->select();
        foreach ($orders as $order){    
            $express_price = \app\order\model\OrderInfo::where("order_sn",$order["order_sn"])->value('express_price') ?: 0;         
            $result = \app\order\model\OrderGoods::getSettleMoney($order, $express_price);
            \app\common\model\Order::where("order_sn",$order["order_sn"])->update([
                 "settle_status"=>1,
                 "settle_money"=> $result["total_settle_money"],         
                 "settle_time"=>  time(),     
             ]);
            //如果还有分销入账，写在这里
             //$order_goods = \app\order\model\OrderGoods::where("order_sn",$order["order_sn"])->select();
        }         
    }
    
}
